#ifndef DAV_GET_H
#define DAV_GET_H
//
#include "base_modul.h"
#include "qxml.h"
#include "basedav.h"
#include "networkdav.h"
//
/*  Save file as dav_get.h  */
/*  incomming class name Dav_Get */
//
#include <QPointer>
//
class Dav_Get : public QObject, public Base_Modul
{
    Q_OBJECT
//
public: 
Dav_Get( NetworkDav *db , const QString remotefile , const QString localfile , QWidget * parent )
{
    loopnummer = -1;
    wakeaborter = false;
    endarrivo = false;
   ///// db = db;
    
    fwriteutf8(localfile,"");  /* make dir if not exist on mirror or reset file to zero  */
    qt_unlink(localfile);  /* remove file */
    
    BeamLogFile = new QFile(localfile); 
    actualurl = remotefile;
    printsecond = 0;
    gostart.start();
    
    dlg = new QProgressDialog(parent,Qt::Window);
    dlg->setCancelButtonText(tr("Abort action Downlod"));
    dlg->setWindowTitle (tr("Download ....."));
    dlg->setLabelText (tr("Download File \"%1\" ").arg( actualurl ));
    ////////dlg->setMinimumDuration(1500);
    dlg->show();
    
    davinfo = new QHttp();
    davinfo->setHost(db->Host(),db->Port());
    davinfo->setUser(db->User(),db->Pass());
    QHttpRequestHeader header("GET", actualurl,1,1);   /* header */
    header.setValue("Host", db->Host());
    header.setValue("User-Agent", WEBAGENTNAME );
    header.setValue("Accept-Charset", "ISO-8859-1,utf-8;q=0.7,*;q=0.7");
    header.setValue("Accept-Language", "it,de-de;q=0.8,it-it;q=0.6,en-us;q=0.4,en;q=0.2");
    header.setValue("Connection", "keep-alive");
    david = davinfo->request(header,0,BeamLogFile);
    
      connect(dlg, SIGNAL(canceled()), this , SLOT(CloseActual()));
      connect(davinfo, SIGNAL(requestFinished(int, bool)), this, SLOT(Wake_Finish(int, bool)));
      connect(davinfo, SIGNAL(dataReadProgress(int, int)), this, SLOT(SendStatus(int, int)));
      connect(davinfo, SIGNAL(responseHeaderReceived(const QHttpResponseHeader &)), this, SLOT(RegisterBackHeader(const QHttpResponseHeader &)));
  
}
void  SetPosition( int position )
{
  loopnummer =   position;  
}
protected:
void DavClose()
{
  BeamLogFile->close();
  davinfo->close();
}
private:
  QString pathinfofile;
  QProgressDialog *dlg;
  QHttp *davinfo;
  int david;
  bool  wakeaborter;
  bool endarrivo;
  int printsecond;
  int loopnummer;
  int statuscode;
  QFile *BeamLogFile;
  QTime gostart;
  QString actualurl;
  QString pathregister;
  QString xmlinfo;
  QString dummypath;
  QString DisplayName;
  QString humanwait;
  QString speeder;

signals:
  void WarningMsg( QString e );
  void LoadGetFileLoop( int next);
  void LoadGetFileReady();
public slots:
    
void CloseActual()
{
     wakeaborter = true;
    
     if (endarrivo) {
      return;
     }
    
       ///////////////////qDebug() << "#### CloseActual...  ->" << wakeaborter; 
       davinfo->abort();
       DavClose();
    
        
    
       emit WarningMsg(tr("Abort on url: %1\nErrorMsg %2").arg(actualurl).arg(davinfo->errorString()));
} 

void  Wake_Finish( int requestId, bool error )
{
   if (requestId != david ) {
     return;
   }
    if (wakeaborter) {
     return;
   }
   
    QHttpResponseHeader lastheader = davinfo->lastResponse();
    statuscode = lastheader.statusCode();
    DavClose();
    delete dlg;
    if (error) {
    emit WarningMsg(tr("Error on url: %1\nErrorMsg %2").arg(actualurl).arg(davinfo->errorString()));
    return;
    } 
    qDebug() << "#### HEADER STATUS CODE  ->" << statuscode; 
    
    if (loopnummer == 0 || loopnummer > 0) {
       int next = loopnummer + 1;
        /////////////delete dlg;
       emit LoadGetFileLoop(next);
       loopnummer = -1;       
     return;
   }
    
   
   emit LoadGetFileReady();
    /*
    if (statuscode == 201 || statuscode == 204 ) {
    RegisterStream();
    } else {
    emit WarningMsg(tr("Error on url: %1\nErrorMsg %2\nHeader Status code %3").arg(actualurl).arg(davinfo->errorString()).arg(statuscode)); 
    }
    */
}
void RegisterBackHeader(const QHttpResponseHeader &responseHeader )
{
   statuscode = responseHeader.statusCode();  
      
}

void  SendStatus( int bytesRead, int totalBytes )
{
    if (wakeaborter) {
     return;
   }
   
   if (bytesRead == totalBytes) {
       //////////QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
   }
   QString elapettime;
   int mmse = gostart.elapsed();
   int sec_el  = mmse / 1000;
   
   if (printsecond == 0) {
   speeder = QString("Wait please calculate Speed...");    
   humanwait = TimeaGo(gostart.elapsed(),0);
   }
   
   
   
    if (printsecond != sec_el) {
        
        qint64 filereadnow = BeamLogFile->pos();  
        
        int kilosec2 = (filereadnow  / 1024) / sec_el;  /* kilo on sec */
        
       //////////// qDebug() << "#### byte0  ->" << bytesRead << "-" << totalBytes;
        ////////qDebug() << "#### byte1  ->" << filereadnow << "-" << totalBytes;
        
       speeder = QString("on %1 Kb/sec.").arg(kilosec2);
       speeder.append(" ");
       if (totalBytes > 0) {
       speeder.append(BiteorMega(totalBytes - bytesRead));
       humanwait = TimeaGo(0,((totalBytes - bytesRead) / 1024) / kilosec2);
       } else {
       speeder = QString("on %1 Kb/sec.").arg(kilosec2);
       speeder.append("Unknow file size");  
       humanwait = TimeaGo(gostart.elapsed(),0);   
       }
      ///////humanwait = TimeaGo(mmse,0);
      printsecond =  sec_el; 
    }
   
    
   elapettime = QString("Time:%1 %2").arg(humanwait).arg(speeder);
   dlg->setLabelText (tr("Download File \"%1\" %2").arg( actualurl ).arg(elapettime));
    
   dlg->setMaximum(totalBytes);
   dlg->setValue(bytesRead);
    
}

};
//
#endif // DAV_GET_H

